<?php

namespace app\admin\controller\dts\wages;

use app\common\controller\Backend;
use think\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
/**
 * 工资管理
 *
 * @icon fa fa-circle-o
 */
class Wages extends Backend
{
    protected $noNeedRight = ['download'];
    /**
     * Wages模型对象
     * @var \app\admin\model\dts\Wages
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\Wages;
        $this->view->assign("categoryList", $this->model->getCategoryList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add() {
        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $path = cdnurl($params['files']);
                
                //获取文件类型
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                if (!in_array($ext, ['xls', 'xlsx'])) {
                    $this->error(__('Unknown data format'));
                }

                if(!in_array($params['category'], ['bar', 'merits'])) {
                    $this->error('发放分类错误');
                }

                $insert = [];

                Db::startTrans();
                try {
                    unset($params['files']);
                    $params['createby'] = $this->auth->nickname;
                    $this->model->save($params);

                    $fileName = 'download/wages_'.$this->model->id.'.'.$ext;
                    file_put_contents($fileName, file_get_contents(cdnurl($path)));

                    $filePath = ROOT_PATH . 'public' . DS . $fileName;
                    if (!is_file($filePath)) {
                        $this->error(__('未找到文件'));
                    }
    
                    $dbname = 'fa_dts_wages_'.$params['category'];
                    
                    $database = \think\Config::get('database.database');
                    $list = db()->query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$dbname, $database]);
                    $fieldArr = [];
                    foreach ($list as $k => $v) {
                        $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                    }

                    //读取模板
                    $reader = IOFactory::createReaderForFile($filePath);
                    $reader->setReadDataOnly(true);
                    $PHPExcel = $reader->load($filePath);

                    $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                    $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                    $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                    $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                    $fields = [];
                    for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                        for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            $fields[] = $val;
                        }
                    }

                    for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                        $values = [];
                        for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            $values[] = is_null($val) ? '' : $val;
                        }
                        $row = [];
                        $temp = array_combine($fields, $values);
                        foreach ($temp as $k => $v) {
                            if (isset($fieldArr[$k]) && $k !== '') {
                                $row[$fieldArr[$k]] = $v;
                                $row['dts_wages_id'] = $this->model->id;
                            }
                        }
                        if($row) {
                            $insert[] = $row;
                        }
                    }

                    if (!$insert) {
                        $this->error(__('未更新任何数据'));
                    }
                    if($params['category'] == 'bar') {
                        $bar = new \app\admin\model\dts\wages\Bar;
                        $bar->saveAll($insert);
                    }
                    if($params['category'] == 'merits') {
                        $merits = new \app\admin\model\dts\wages\Merits;
                        $merits->saveAll($insert);
                    }

                    $push_text_arr = array_column($insert, 'username');
                    $adminList = Db::name('admin')->field('id')->where('nickname', 'in', $push_text_arr)->select();
                    $push_id_arr = array_column((array)$adminList, 'id');
                    $data = [
                        'title' => $params['title'], 'type' => 1, 'content' => $params['category'].','.$this->model->id, 'push_text' => implode(',', $push_text_arr), 'teacher_notice_range' => implode(',', $push_id_arr), 'admin_id' => $this->auth->id
                    ];
                    \app\admin\model\dts\garden\Notice::create($data);

                    Db::commit();
                } catch (\Exception $e) {
                    unlink($filePath);
                    Db::rollback();
                    $this->error($e->getMessage());

                }

                unlink($filePath);
                $this->success();
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    protected function after_del($v)
    {
        \app\admin\model\dts\wages\Bar::where('dts_wages_id', $v['id'])->delete();
        \app\admin\model\dts\wages\Merits::where('dts_wages_id', $v['id'])->delete();
        \app\admin\model\dts\garden\Notice::where(['type' => 1])->whereRaw('FIND_IN_SET('.$v['id'].',content) > 0')->delete();
    }

    public function download()
    {

        $tmpDir =  ROOT_PATH . 'tmp'; //产生一个临时文件，用于缓存下载文件
        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }

        //----------开始------------
        $filename = '工资、绩效导入模板.zip'; //下载的默认文件名
        $zipNameUrl = $tmpDir .'/'. $filename; // 文件路径

        // 生成文件
        $zip = new \ZipArchive();
        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
        }

        $query = [];
        $params = $this->request->get('params');
        if($params) {
            $query = json_decode($params, true);
            if(isset($query['createtime'])) {
                $time = explode(' - ', $query['createtime']);
                $query['createtime'] = ['between' => [$time[0], $time[1]]];
            }
        }

        //获取文件
        $bar_template_url = '/template/工资.xlsx';
        $merits_template_url = '/template/绩效.xlsx';
        $list = [$bar_template_url, $merits_template_url];

        foreach ($list as $url) {
            $file = ROOT_PATH . 'public' . $url;
            $isFile = file_exists($file);
            if ($isFile) {
                //抓取图片内容
                $fileContent = file_get_contents($file);
                //添加图片
                $zip->addFromString(basename($file), $fileContent);
            }
        }
        //----------关闭------------
        $zip->close();

        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:' . gmdate('D, d M Y H:i:s') . 'GMT');
        header("Content-Description: File Transfer");
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-type:application/zip');
        header('Content-Disposition:attachment; filename="' . $filename . '"'); //设置下载的默认文件名
        header('Content-length:' . filesize($zipNameUrl));

        @flush();
        @ob_flush();

        @readfile($zipNameUrl);
        @unlink($zipNameUrl);

        exit();
    }

}
